package jiazhong.hfl20250308;

import java.util.ArrayList;
import java.util.Scanner;

//7.给你⼀个长度为 n 的整数集合 nums 和 ⼀个⽬标值 与 target 最接近。请你从 nums 中选出三个整数,使它们的和与 target 最接近
public class NumSum {

    public static Scanner scanner = new Scanner(System.in);

    public static void find(ArrayList<Integer> list, int target) {
        int n = list.size();// 集合长度
        int num1 = -1, num2 = -1, num3 = -1;// 三个整数用来带出和最接近的三个整数
        int[] nums = new int[n];
        for (int i = 0; i < n; i++) {
            nums[i] = list.get(i);
        }
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < n - 2; i++) {// 枚举第一个整数
            for (int j = i + 1; j < n - 1; j++) {// 枚举第二个整数
                for (int k = j + 1; k < n; k++) {// 枚举第三个整数
                    int sum = nums[i] + nums[j] + nums[k];
                    if (Math.abs(sum - target) < min) {
                        min = Math.abs(sum - target);// 记录最小差值
                        num1 = nums[i];
                        num2 = nums[j];
                        num3 = nums[k];
                    }
                }
            }
        }
        System.out.println("和最接近的三个数为：" + num1 + " " + num2 + " " + num3);
    }

    public static void main(String[] args) {
        System.out.print("请输入集合长度：");
        int n = scanner.nextInt();
        System.out.print("请输入target：");
        int target = scanner.nextInt();
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 1; i <= n; i++) {
            list.add((int) (Math.random() * 10 + 1));
        }
        System.out.println(list);
        find(list, target);
    }
}
